// PlayerDataManager.java
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;

public class PlayerDataManager {
    private static final String PLAYER_DATA_FILE = "player_data.txt";
    private static final String SCORE_DATA_FILE = "score_data.txt";

    // 保存玩家名字（保持不变）
    public static void savePlayerName(String name) {
        try {
            Files.write(Paths.get(PLAYER_DATA_FILE), name.getBytes());
        } catch (IOException e) {
            System.err.println("保存玩家名字失败: " + e.getMessage());
        }
    }

    // 读取玩家名字（保持不变）
    public static String loadPlayerName() {
        try {
            if (Files.exists(Paths.get(PLAYER_DATA_FILE))) {
                return new String(Files.readAllBytes(Paths.get(PLAYER_DATA_FILE)));
            }
        } catch (IOException e) {
            System.err.println("读取玩家名字失败: " + e.getMessage());
        }
        return null;
    }

    // 检查是否有保存的玩家（保持不变）
    public static boolean hasSavedPlayer() {
        return Files.exists(Paths.get(PLAYER_DATA_FILE));
    }

    // 修正保存分数方法
    public static void saveScore(int score) {
        try {
            String playerName = loadPlayerName();
            if (playerName == null) return;

            // 1. 读取现有记录
            List<ScoreEntry> allScores = new ArrayList<>();
            if (Files.exists(Paths.get(SCORE_DATA_FILE))) {
                // 逐行读取文件
                List<String> lines = Files.readAllLines(Paths.get(SCORE_DATA_FILE));
                for (String line : lines) {
                    // 按"-"分割分数和玩家名（限制分割2部分）
                    String[] parts = line.split("-", 2);
                    if (parts.length == 2) {
                        // 转换为ScoreEntry对象
                        allScores.add(new ScoreEntry(
                                parts[1].trim(),          // 玩家名
                                Integer.parseInt(parts[0]) // 分数
                        ));
                    }
                }
            }

            // 2. 添加新记录
            allScores.add(new ScoreEntry(playerName, score));

            // 3. 去重处理：只保留每个玩家的最高分
            Map<String, Integer> bestScores = new HashMap<>();
            for (ScoreEntry entry : allScores) {
                // 如果玩家不存在于map，或当前分数更高，则更新
                if (!bestScores.containsKey(entry.name) ||
                        bestScores.get(entry.name) < entry.score) {
                    bestScores.put(entry.name, entry.score);
                }
            }

            // 4. 转换为列表并排序
            List<ScoreEntry> sortedScores = bestScores.entrySet().stream()
                    .map(entry -> new ScoreEntry(entry.getKey(), entry.getValue()))
                    .sorted((a, b) -> Integer.compare(b.score, a.score)) // 降序排序
                    .collect(Collectors.toList());

            // 5. 写入文件（只保留前3名）
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < Math.min(3, sortedScores.size()); i++) {
                ScoreEntry entry = sortedScores.get(i);
                content.append(entry.score)
                        .append("-")
                        .append(entry.name)
                        .append("\n");
            }
            Files.write(Paths.get(SCORE_DATA_FILE), content.toString().getBytes());

        } catch (IOException e) {
            System.err.println("保存分数失败: " + e.getMessage());
        }
    }

    // 修正读取方法
    public static List<ScoreEntry> loadScores() {
        List<ScoreEntry> scores = new ArrayList<>();
        try {
            if (Files.exists(Paths.get(SCORE_DATA_FILE))) {
                // 使用Set来自动去重
                Set<String> uniqueLines = new LinkedHashSet<>(
                        Files.readAllLines(Paths.get(SCORE_DATA_FILE))
                );

                for (String line : uniqueLines) {
                    String[] parts = line.split("-", 2);
                    if (parts.length == 2) {
                        scores.add(new ScoreEntry(parts[1].trim(), Integer.parseInt(parts[0])));
                    }
                }

                // 按分数降序排序
                scores.sort((a, b) -> Integer.compare(b.score, a.score));

                // 只返回前3名
                return scores.size() > 3 ? scores.subList(0, 3) : scores;
            }
        } catch (IOException e) {
            System.err.println("读取排行榜失败: " + e.getMessage());
        }
        return scores;
    }

    // 分数条目类（实现Comparable接口）
    public static class ScoreEntry implements Comparable<ScoreEntry> {
        public String name;
        public int score;

        public ScoreEntry(String name, int score) {
            this.name = name;
            this.score = score;
        }

        @Override
        public int compareTo(ScoreEntry other) {
            // 按分数降序排列
            return Integer.compare(other.score, this.score);
        }
    }
}